<template>

  <div>
    <el-form :inline="true" style="margin-top:5px ">
      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-input
            v-model="search"
            placeholder="输入游戏名称关键字搜索"
            align="right"
            height="80px">
          <!--        <template slot="prepend" icon="el-icon-search">搜索</template>-->
          <el-button slot="append" icon="el-icon-search" style="float: left"></el-button>
        </el-input>
      </el-form-item>
    </el-form>
<!--    表格-->
    <el-table
        ref="multipleTable"
        :data="tableData.filter(data => !search || data.gameName.toLowerCase().includes(search.toLowerCase()))"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        >
      <el-table-column
          prop="gameId"
          label="游戏id"
          width="80"
      >
      </el-table-column>
      <el-table-column
          prop="gameImg"
          label="图片"
          width="120">
        <template slot-scope="scope">
        <img
            preview
            :src="'http://localhost:8080/GameStore/images/'+scope.row.gameImg"
            style="width: 80px;height: 80px;border-radius: 8px"
        >
      </template>
      </el-table-column>

      <el-table-column
          prop="gameName"
          label="游戏名称"
          width="120"
      >
      </el-table-column>


      <el-table-column
          prop="gameType"
          label="游戏类型"
          :filters="[{ text: '角色扮演', value: '角色扮演' }, { text: '休闲益智', value: '休闲益智' },{ text: '经营策略', value: '经营策略' },{ text: '体育竞技', value: '体育竞技' },{ text: '动作射击', value: '动作射击' },{ text: '棋牌桌游', value: '棋牌桌游' }]"
          :filter-method="filterTag"
          filter-placement="bottom-end">
      </el-table-column>

      <el-table-column
          :show-overflow-tooltip="true"
          prop="description"
          label="描述"
          width="500">
      </el-table-column>

      <el-table-column
          prop="price"
          label="价格"
          width="120"
      sortable>
        <template slot-scope="scope">
          ¥{{scope.row.price}}
        </template>
      </el-table-column>

      <el-table-column
          prop="saleCount"
          label="销量"
          width="120"
      sortable>
      </el-table-column>

      <el-table-column
          prop="icon"
          label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="确定删除该游戏吗？" @confirm="deleteGame(scope.row.gameId)">
              <el-button type="text" slot="reference" @click="">删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>

    </el-table>

    <!--    分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[1,5,10,100,200,1000,10000]"
        :page-size="size"
        layout="total, sizes, prev, pager, next"
        :total="total"
        style="float: right;margin-bottom: 20px">
    </el-pagination>

    <!--新增对话框-->
    <el-dialog
        title="新增游戏"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">

      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-editForm">

        <el-form-item label="图片" prop="gameImg" label-width="100px" >


          <el-upload ref="upload" action="#" multiple :limit="1" :file-list="fileList" list-type="picture-card"
                     :on-preview="handlePictureCardPreview" :on-change="OnChange" :on-remove="handleRemove" :on-exceed="handleExceed"
                     accept="image/jpeg,image/png" :auto-upload="false">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">请上1张传游戏略缩图，只能上传jpg/png文件，单张图片不超过5M
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible2" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>

          <el-upload ref="upload" action="#" multiple :limit="3" :file-list="fileList1" list-type="picture-card"
                     :on-preview="handlePictureCardPreview1" :on-change="OnChange1" :on-remove="handleRemove1" :on-exceed="handleExceed"
                     accept="image/jpeg,image/png" :auto-upload="false">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">请上3张传游戏详情图，只能上传jpg/png文件，单张图片不超过5M
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible2" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>



        </el-form-item>
        <el-form-item label="游戏名" prop="gameName" label-width="100px">
          <el-input v-model="editForm.gameName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="类型"  :required="true">
          <el-select v-model="editForm.gameType" placeholder="请选择游戏类型">
            <el-option label="角色扮演" value="角色扮演"></el-option>
            <el-option label="休闲益智" value="休闲益智"></el-option>
            <el-option label="经营策略" value="经营策略"></el-option>
            <el-option label="体育竞技" value="体育竞技"></el-option>
            <el-option label="动作射击" value="动作射击"></el-option>
            <el-option label="棋牌桌游" value="棋牌桌游"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price" label-width="100px">
          <el-input v-model="editForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description" label-width="100px">
          <el-input type="textarea" v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')">确认新增</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>



    </el-dialog>


    <!--编辑对话框-->
    <el-dialog
        title="编辑游戏"
        :visible.sync="dialogVisible1"
        width="600px"
        :before-close="handleClose1">
      <el-form :model="editForm1" :rules="editFormRules1" ref="editForm1" label-width="100px" class="demo-editForm">
        <el-form-item label="游戏名" prop="gameName" label-width="100px">
          <el-input v-model="editForm1.gameName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="类型" :required="true">
          <el-select v-model="editForm1.gameType" placeholder="请选择游戏类型">
            <el-option label="角色扮演" value="角色扮演"></el-option>
            <el-option label="休闲益智" value="休闲益智"></el-option>
            <el-option label="经营策略" value="经营策略"></el-option>
            <el-option label="体育竞技" value="体育竞技"></el-option>
            <el-option label="动作射击" value="动作射击"></el-option>
            <el-option label="棋牌桌游" value="棋牌桌游"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price" label-width="100px">
          <el-input v-model="editForm1.price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item  label="描述" prop="description" label-width="100px">
          <el-input type="textarea" v-model="editForm1.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm1('editForm1')" style="margin: auto">确认修改</el-button>
          <el-button @click="resetForm1()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "goodsManage",
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible2: false,
      search:'',
      fileList: [],
fileList1: [],
      forbiddenForm: {
        userId:'',
        status:''
      },
      fileUrlList:[],
      total: 0,
      size: 100,
      current: 1,
      dialogVisible:false,
      dialogVisible1:false,
      editForm: {
        gameId:'',
        saleCount:'',
        gameName:'',
        price:'',
        gameImg:'',
        description:'',
        gameType:'',
      },
      editForm1: {
        gameId:'',
        saleCount:'',
        gameName:'',
        price:'',
        gameImg:'',
        description:'',
        gameType:'',
      },
      editFormRules: {
        saleCount: [
          {required: true, message: '请输入折扣', trigger: 'blur'}
        ],
        gameName: [
          {required: true, message: '请输入游戏名称', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'}
        ],
        gameType: [
          {required: true, message: '请输入游戏类型', trigger:'blur'}
        ],
        description: [
          {required: true, message: '请输入游戏描述', trigger: 'blur'}
        ],

      },
      editFormRules1: {
        saleCount: [
          {required: true, message: '请输入折扣', trigger: 'blur'}
        ],
        gameName: [
          {required: true, message: '请输入游戏名称', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'}
        ],
        gameType: [
          {required: true, message: '请输入游戏类型', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入游戏描述', trigger: 'blur'}
        ],

      },

      tableData: [

      ],

    }
  },
  created(){
    this.getGameList();
  },
  methods:{
    OnChange(file, fileList) {
      const isType = file.type === 'image/jpeg' || 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
        fileList.pop()
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
        fileList.pop()
      }
      this.fileList.push(file)
      this.hideUpload = fileList.length >= this.limit

    },OnChange1(file, fileList) {
      const isType = file.type === 'image/jpeg' || 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
        fileList.pop()
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
        fileList.pop()
      }
      this.fileList1.push(file)
      this.hideUpload = fileList.length >= this.limit

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },handlePictureCardPreview1(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    filterTag(value, row) {
      return row.gameType === value;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList=fileList
    }, handleRemove1(file, fileList) {
      console.log(file, fileList);
      this.fileList1=fileList
    },
    handlePreview(file) {
      console.log(file);
    },
    deleteGame(gameId){
      this.$axios.post('/game/delete/'+gameId).then(res => {
        if(res.data.status === 200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success',
          });
          this.getGameList()
        }
      })
    },
    editHandle(row){
    this.editForm1=row
      this.dialogVisible1 = true;
    },
    submitForm1(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
            this.$axios.post('/game/modify' , this.editForm1)
                .then(res => {

                  if(res.data.status === 200) {
                    this.$message({
                      showClose: true,
                      message: '修改成功',
                      type: 'success',
                    });
                    this.getGameList()
                  }
                  this.dialogVisible1 = false
                })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getGameList() {
      this.$axios.get('/allGames',{
        params:{
          size:this.size,
          current:this.current
        }
      }).then(res => {
        this.tableData = res.data.gameList
        this.total= res.data.total
        this.current= res.data.current
      })
    },
    submitForm(formName) {

      if(this.fileList.length ===0||this.fileList1.length !=3){
        this.$message({
          showClose: true,
          message: '请上传一张主图和三张详情图',
          type: 'error',
        });
      }else{
      //上传图片
        let formData = new FormData(); //  用FormData存放上传文件
        this.fileList.forEach(file => {
          formData.append('files', file.raw)
        })
      this.fileList1.forEach(file => {
          formData.append('files', file.raw)
        })
      this.$axios.post('/gameImg/upload' , formData)
          .then(res => {
              this.fileUrlList=res.data.fileUrlList



            //上传表单
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let formData = new FormData();
                formData.append('gameName',this.editForm.gameName);
                formData.append('gameType',this.editForm.gameType);
                formData.append('price',this.editForm.price);
                formData.append('description',this.editForm.description);
                formData.append('fileUrlList',res.data.fileUrlList);
                formData.append('saleCount',0);
                this.$axios.post('/game/add' , formData)
                    .then(res => {
                      if(res.data.status === 200) {
                        this.$message({
                          showClose: true,
                          message: '新增成功',
                          type: 'success',
                        });
                        this.getGameList();
                        this.editForm={};
                        this.fileUrlList=[];
                        this.fileList=[];
                        this.fileList1=[];
                      }
                      this.dialogVisible = false
                    })
              } else {
                console.log('error submit!!');
                return false;
              }
            });




          })

    }},
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.editForm = {}
      this.fileList=[]
      this.fileList1=[]
    },
    resetForm1(formName) {
      this.dialogVisible1 = false
    },
    handleClose() {
      this.resetForm('editForm')
    },
    handleClose1() {
      this.resetForm1('editForm1')
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size=val;
      this.getGameList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current=val;
      this.getGameList();
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-pagination {
  float: right;
  margin-top: 22px;
}

</style>